package com.truongnha.clienttn.data.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class CreateDatabase {

	public static final String TAG = "DBAdapter";

	public static final String KEY_ID = "_id";
	public static final String KEY_NAME = "name";

	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDB;

	private static final String DATABASE_NAME = "truongnha";
	private static final int DATABASE_VERSION = 2;

	private final Context mContext;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			AccountScheme.onCreate(db);
			AttendScheme.onCreate(db);
			StudentMarkScheme.onCreate(db);
			StudentSubjectScheme.onCreate(db);
			ClassScheme.onCreate(db);
			TeacherAttendScheme.onCreate(db);
			SavedAccountScheme.onCreate(db);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.i(TAG, "Upgrading DB");
			db.execSQL("DROP TABLE IF EXISTS " + AccountScheme.TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + AttendScheme.TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + StudentMarkScheme.TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS "
					+ StudentSubjectScheme.TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + ClassScheme.TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + TeacherAttendScheme.TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + SavedAccountScheme.TABLE_NAME);
			onCreate(db);
		}
	}

	public CreateDatabase(Context ctx) {
		this.mContext = ctx;
		mDbHelper = new DatabaseHelper(mContext, DATABASE_NAME, null,
				DATABASE_VERSION);
	}

	public SQLiteDatabase open() {
		if (mDB == null || !mDB.isOpen()) {
			try {
				mDB = mDbHelper.getWritableDatabase();
			} catch (Exception e) {
				Log.d("log error", e.toString());
				e.printStackTrace();
			}
		}
		return mDB;
	}

	public SQLiteDatabase getDatabase() {
		return mDB;
	}

	public void close() {
		mDbHelper.close();
	}
}
